import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, Alert, Divider} from 'antd';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import {PAGE, TABLE, ROWSELECTION_FIXED_COLUMN_WIDTH, FORM_OPTIONS} from '../constants';
import WrappedTag from '../common/WrappedTag';
import difference from 'lodash/difference';
import {getListApply} from './api';
import {conventEnumValueToString} from '../utils';
import {PAGINATION_OPTIONS} from './utils';
import {packingListType, packingType} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import TextArea from 'Shared/components/TextArea';
const FormItem = Form.Item;
class PackingSelectPanel extends React.PureComponent {
    state = {
        condition: {
            code: '',
            partOrderTypeId: '',
            partOrderType: undefined,
            dealerCode: '',
            palletCodes: [],
            pickingListCode: [],
            partSaleOrderCode: []
        },
        conditionOfPage: {
            pageIndex: 0,
            pageSize: 100,
            sortBy: 'code',
            sortOrder: 'ascend'
        },
        //点击查询后的条件,用于分页查询
        list: {
            isFetching: false,
            total: 0,
            data: []
        },
        selectedRowKeys: [],
        selectedRows: [],
        showTags: false
    };
    handleFilterChange = (value, id) => {
        const newCondition = Object.assign({}, this.state.condition, {
            [id]: value
        });
        this.setState({
            condition: newCondition
        });
    };

    handleFilterPressEnter = (value, id) => {
        this.setState({
            condition: {
                ...this.state.condition,
                [id]: value
            }
        }, this.clickQueryBtn);
    };
    clickQueryBtn = () => {
        this.setState({
            conditionOfPage: Object.assign(
                {},
                this.state.conditionOfPage,
                {
                    pageIndex: PAGE.index
                },
                this.state.condition
            )
        });
        this.asyncQuery(
            Object.assign({}, this.state.condition, {
                pageSize: this.state.conditionOfPage.pageSize,
                pageIndex: PAGE.index,
                sortBy: this.state.conditionOfPage.sortBy,
                sortOrder: this.state.conditionOfPage.sortOrder
            })
        );
    };
    asyncQuery = condition => {
        this.setState({
            list: {
                ...this.state.list,
                isFetching: true
            }
        });
        const {sortBy, sortOrder, ...query} = condition;
        if(sortBy && sortOrder) {
            query.sortField = sortBy;
            query.isDesc = sortOrder === 'descend';
        }
        getListApply({
            ...query,
            dealerId: this.props.dealerId,
            isCabinet: true,
            isHadCabinet: false,
            status: [packingListType.包装完成]
        }).then(res => {
            if(res.ok)
                this.setState({
                    list: {
                        isFetching: false,
                        total: res.data.totalElements,
                        data: res.data.content
                    }
                });
            else
                this.setState({
                    list: {
                        isFetching: false,
                        total: 0,
                        data: []
                    }
                });
        });
    };
    toggleShowTags = () => {
        this.setState({
            showTags: !this.state.showTags
        });
    };
    onChangeSort = (pagination, filters, sorter) => {
        const {pageIndex, pageSize} = this.state.conditionOfPage;
        if(pagination.current - 1 === pageIndex && pagination.pageSize === pageSize) {
            const {field: sortBy, order: sortOrder} = sorter;
            this.setState({
                conditionOfPage: {
                    ...this.state.conditionOfPage,
                    sortBy,
                    sortOrder
                }
            }, this.clickQueryBtn);
        }
    };
    onSelectChange = (selectedRowKeys, selectedRows) => {
        const data = this.state.selectedRows;
        const preSelectedKeys = this.state.selectedRowKeys; // 勾选行

        if(selectedRowKeys.length > preSelectedKeys.length)
            selectedRows.forEach(v => {
                if(data.findIndex(d => d.id === v.id) === -1) data.push(v);
            });
        else {
            // 取消勾选
            const diffKeys = difference(preSelectedKeys, selectedRowKeys);
            diffKeys.forEach(k => {
                const index = data.findIndex(d => d.id === k);
                data.splice(index, 1);
            });
        }
        this.setState({
            selectedRowKeys,
            selectedRows: data
        });
    };
    onConfirm = () => {
        this.props.onSelect(this.state.selectedRows);
    };
    onClearAll = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    };
    onPageSizeChange = (pageIndex, pageSize) => {
        const newCondition = Object.assign({}, this.state.conditionOfPage, {
            pageSize,
            pageIndex: PAGE.index
        });
        this.setState({
            conditionOfPage: newCondition
        });
        this.asyncQuery(newCondition);
    };
    onPageIndexChange = pageIndex => {
        const newCondition = Object.assign({}, this.state.conditionOfPage, {
            pageIndex: pageIndex - 1
        });
        this.setState({
            conditionOfPage: newCondition
        });
        this.asyncQuery(newCondition);
    };
    onDelete = id => {
        const keys = this.state.selectedRowKeys.filter(k => k !== id);
        const rows = this.state.selectedRows.filter(r => r.id !== id);
        this.setState({
            selectedRowKeys: [...keys],
            selectedRows: [...rows]
        });
    };

    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.code',
                    defaultMessage: '箱单号'
                }),
                sorter: true,
                dataIndex: 'code',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.dealer',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealer',
                render: (text, record) => `(${record.dealerCode})${record.dealerName}`
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.partSaleOrderCode',
                    defaultMessage: '订单编号'
                }),
                sorter: true,
                dataIndex: 'partSaleOrderCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.partOrderTypeName',
                    defaultMessage: '订单类型'
                }),
                dataIndex: 'partOrderTypeName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.pickingListCodes',
                    defaultMessage: '备料单号'
                }),
                dataIndex: 'pickingListCodes',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.palletCodes',
                    defaultMessage: '托盘号'
                }),
                dataIndex: 'palletCodes',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.packingType',
                    defaultMessage: '包装类型'
                }),
                dataIndex: 'packingType',
                render: text => conventEnumValueToString(packingType, text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.container',
                    defaultMessage: '包装规格'
                }),
                dataIndex: 'container',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.length',
                    defaultMessage: '长度（mm）'
                }),
                dataIndex: 'length',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.width',
                    defaultMessage: '宽度（mm）'
                }),
                dataIndex: 'width',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.height',
                    defaultMessage: '高度（mm）'
                }),
                dataIndex: 'height',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.volume',
                    defaultMessage: '体积（m³）'
                }),
                dataIndex: 'volume',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.netWeight',
                    defaultMessage: '净重（kg）'
                }),
                dataIndex: 'netWeight',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'PackingSelectPanel.column.grossWeight',
                    defaultMessage: '毛重（kg）'
                }),
                dataIndex: 'grossWeight',
            },
        ];

        const pagination = {
            total: this.state.list.total,
            pageSize: this.state.conditionOfPage.pageSize,
            current: this.state.conditionOfPage.pageIndex + 1,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            type: 'checkbox',
            getCheckboxProps: record => ({
                disabled: this.props.currentSelectRowKeys.includes(record.id)
            }),
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: this.onSelectChange
        };
        const alertMessage = (
            <div>
                <span>
                    {this.props.intl.formatMessage({
                        id: 'PackingSelectPanel.alertMessage.span',
                        defaultMessage: '已选择'
                    })}
                    <a onClick={this.toggleShowTags}>
                        {this.state.selectedRows.length}
                        {this.props.intl.formatMessage({
                            id: 'PackingSelectPanel.alertMessage.a.number',
                            defaultMessage: '项'
                        })}
                    </a>
                    {this.props.intl.formatMessage({
                        id: 'PackingSelectPanel.alertMessage.comma',
                        defaultMessage: '，'
                    })}
                    <a onClick={this.onClearAll} className={styles.clearAllTag}>
                        {this.props.intl.formatMessage({
                            id: 'PackingSelectPanel.alertMessage.deleteAll',
                            defaultMessage: '清除选择'
                        })}
                    </a>
                    <Button
                        size="small"
                        type="primary"
                        className={styles.partBtn}
                        onClick={this.onConfirm}>
                        {this.props.intl.formatMessage({
                            id: 'PackingSelectPanel.btn.confirm',
                            defaultMessage: '确认'
                        })}
                    </Button>
                </span>
                {this.state.showTags && (
                    <div className={styles.partTag}>
                        {this.state.selectedRows.map(r => (
                            <WrappedTag key={r.id} closable id={r.id} onClose={this.onDelete}>
                                {r.code}
                            </WrappedTag>
                        ))}
                    </div>
                )}
            </div>
        );
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'PackingSelectPanel.code',
                                    defaultMessage: '箱单号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput id="code" value={this.state.condition.code}
                                    onPressEnter={this.handleFilterPressEnter} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'PackingSelectPanel.partSaleOrderCode',
                                    defaultMessage: '订单编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="partSaleOrderCode"
                                    placeholder={this.props.intl.formatMessage({
                                        id: 'PackingSelectPanel.form.palletCodes.placeholder',
                                        defaultMessage: '最多输入1000个，以回车隔开'
                                    })}
                                    value={this.state.condition.partSaleOrderCode}
                                    onBlur={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'PackingSelectPanel.palletCodes',
                                    defaultMessage: '托盘号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="palletCodes"
                                    placeholder={this.props.intl.formatMessage({
                                        id: 'PackingSelectPanel.form.palletCodes.placeholder',
                                        defaultMessage: '最多输入1000个，以回车隔开'
                                    })}
                                    value={this.state.condition.palletCodes}
                                    onBlur={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'PackingSelectPanel.pickingListCode',
                                    defaultMessage: '备料单号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="pickingListCode"
                                    placeholder={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.pickingListCode.placeholder',
                                        defaultMessage: '最多输入1000个，以回车隔开'
                                    })}
                                    value={this.state.condition.pickingListCode}
                                    onBlur={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'PackingSelectPanel.partOrderTypeId',
                                    defaultMessage: '订单类型'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="partOrderTypeId"
                                    value={this.state.condition.partOrderTypeId}
                                    options={this.props.types}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={8} className={styles.selectPanelBtn}>
                            <Button key="query" type="primary" onClick={this.clickQueryBtn} loading={this.state.list.isFetching}>
                                {this.props.intl.formatMessage({
                                    id: 'PackingSelectPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                        </Col>
                    </Row>
                </Form>
                <Divider className={styles.divider} />
                <Alert className={styles.alertMargin} type="info" message={alertMessage} showIcon />
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.state.list.data}
                    rowKey="id"
                    rowSelection={rowSelection}
                    pagination={pagination}
                    onChange={this.onChangeSort}
                    loading={this.state.list.isFetching}
                    {...TABLE}/>
            </div>
        );
    }
}
PackingSelectPanel.propTypes = {
    currentSelectRowKeys: PropTypes.array.isRequired,
    onSelect: PropTypes.func.isRequired,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
};
import {connect} from 'react-redux';
import {createSelector} from 'reselect';
const getTypes = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'partSaleOrderTypes']),
    data => {
        const types = data.toJS() || [];
        return types.map(item => ({
            text: `(${item.typeCode}) ${item.typeName}`,
            value: item.id
        }));
    }
);
const mapStateToProps = state => ({
    types: getTypes(state),
});
export default connect(mapStateToProps, null)(injectIntl(PackingSelectPanel));
